Attribute VB_Name = "modMultiForm"
Option Explicit

''=======
'' Usage:
''=======
'Private Sub cmdSetForm_Click(Index As Integer)
'    Select Case Index
'        Case 0
'            SwitchForm Picture1, frmSub1
'        Case 1
'            SwitchForm Picture1, frmSub2
'        Case 2
'            SwitchForm Picture1, frmSub3
'        Case 3
'            UnloadForm
'        Case 4
'            LoadForm Picture1, frmSub1
'    End Select
'    'Set focus on the main form
'    frmMain.SetFocus
'End Sub
'
'Private Sub Form_Load()
'    LoadForm Picture1, frmSub1
'End Sub
'
'Private Sub Form_Unload(Cancel As Integer)
'    UnloadForm
'End Sub

Public Declare Function SetParent Lib "user32" (ByVal hWndChild As Long, ByVal hWndNewParent As Long) As Long
Public CurrentForm As Object
Public Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Public Const GWL_HWNDPARENT = (-8)

Public Function isEmbeddedForm(frmMain As Form, frmEmbed As Form, picEmbedForm As PictureBox) As Boolean
    Dim lParentHandle As Long
    Dim lPicBoxHandle As Long
    Dim lAppHandle As Long
    Dim bEmbedded As Boolean
    Dim bDialogBox As Boolean
    Dim bError As Boolean
    
    isEmbeddedForm = False
   
    bError = False
    lParentHandle = GetWindowLong(frmEmbed.hwnd, GWL_HWNDPARENT)
    lPicBoxHandle = picEmbedForm.hwnd
    lAppHandle = GetWindowLong(frmMain.hwnd, GWL_HWNDPARENT)
    bEmbedded = CBool(lParentHandle = lPicBoxHandle)
    bDialogBox = CBool(lParentHandle = lAppHandle)
    If (bEmbedded = bDialogBox) Then
        bError = True
    Else
        isEmbeddedForm = bEmbedded
    End If
End Function

Public Sub LoadForm(picFrame As PictureBox, oForm As Object)
    Dim Form As Form

    Load oForm
    Set CurrentForm = oForm
    Set Form = oForm

    'Form.BorderStyle = 0
    'Form.Top = picFrame.Top
    Form.Top = 0
    Form.Left = 0

    SetParent Form.hwnd, picFrame.hwnd
    Form.Show

End Sub

Public Sub SwitchForm(picFrame As PictureBox, NewForm As Object)
    Dim Form As Form                    'Form object

    Unload CurrentForm                  'Unload the old form that is embedded
    Load NewForm                        'Load the new form into memory

    Set Form = NewForm                  'Access the object NewForm from Form (To access form properties)
    'Form.BorderStyle = 0
    Form.Top = 0
    'Form.Top = picFrame.Top             'Align the top of the form
    Form.Left = 0                       'Align the left of the form

    SetParent Form.hwnd, picFrame.hwnd  'Set the new form as a child of frmMain
    Form.Show 'Show the form

    Set CurrentForm = NewForm           'Store the current form in a global so it can be unloaded when the program exits
End Sub

Public Sub UnloadForm()
    Unload CurrentForm
End Sub
